/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.veditor.view.ev;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import offset.nodes.client.veditor.model.ev.DataElementView;
import offset.nodes.client.editor.view.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.Element;
import offset.nodes.Constants;
import offset.nodes.client.editor.Editor;
import offset.nodes.client.veditor.model.DataModel;
import offset.nodes.client.editor.model.messages.GetQueryResults;
import offset.nodes.client.model.HttpUtils;
import offset.nodes.client.model.ServerModel;
import offset.nodes.client.view.SimpleDialog;

/**
 *
 * @author Walter Lütgenau
 */
public class SelectQueryChooser implements DataElementView {

    DataElementViewContext context = null;

    public SelectQueryChooser() {
    }

    /**
     * Calle by VirtualBlock, when a view shall be used to retrieve the new value for a data element.
     * @param context The virtual block and the element
     */
    public void setContext(DataElementViewContext context) {
        try {
            this.context = context;

            // retrieve some basic items used below
            String value = context.getVirtualBlock().getModel().getDocument().getText(
                    context.getElement().getStartOffset(), context.getElement().getEndOffset() - context.getElement().getStartOffset() - 1);

            String dataPath = context.getVirtualBlock().getModel().getData(context.getElement());
            String[] options = (String[]) context.getVirtualBlock().getViewRegistry().get(dataPath);
            if (options == null) {
                Map properties = context.getVirtualBlock().getModel().getProperties();
                String serverUrl = (String) properties.get(Editor.PROP_UPLOAD_TO);

                ServerModel server = new ServerModel(new URL(serverUrl));

                GetQueryResults.Request request = new GetQueryResults.Request();
                request.setInstancePath((String) properties.get(Editor.PROP_INSTANCE_PATH));
                request.setQueryName(context.getVirtualBlock().getModel().getElementAction(context.getElement()));
                String documentPath = (String) properties.get(Editor.PROP_DOCUMENT_PATH);
                if (documentPath == null || documentPath.length() == 0)
                    request.setReferenceUuid(getDocumentUuid((String) properties.get(Editor.PROP_DOCUMENT_URL)));
                else
                    request.setReferencePath(documentPath);

                GetQueryResults.Response response = (GetQueryResults.Response) server.sendRequest(request);
                options = response.getResults();
                context.getVirtualBlock().getViewRegistry().put(dataPath, options);
            }

            // display the option pane with the values
            String title = ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle").getString("selectQuery.title"); // NOI18N
            SelectQueryPanel panel = new SelectQueryPanel(options, value);
            SimpleDialog dialog = new SimpleDialog(null, true, panel);
            panel.setContainer(dialog);
            dialog.setSize(420, 230);
            dialog.setLocation(100, 100);
            dialog.setVisible(true);
            dialog.setTitle(title);

            if (dialog.getReturnStatus() == SimpleDialog.OK) {
                String selected = panel.getSelectedValue();
                substituteContent(context.getElement(), selected);
            }
        } catch (Exception ex) {
            Logger.getLogger(SelectQueryChooser.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    /**
     * Determine the document's uuid from the URL, if it is encoded.
     * 
     * @param documentUrlString
     * @return
     * @throws MalformedURLException
     */
    protected String getDocumentUuid(String documentUrlString) throws MalformedURLException {
        HashMap<String, String> parameters = HttpUtils.getParameters(documentUrlString);
        return parameters.get(Constants.PAR_DATA_REFERENCE);
    }

    /**
     * Substitute the content of the element with the selected enumerated value
     * @param e The element
     * @param value The value
     * @throws java.lang.Exception
     */
    protected void substituteContent(Element e, String value) throws Exception {
        StringBuffer buf = new StringBuffer();
        DataModel model = context.getVirtualBlock().getModel();

        buf.append(model.getStartTag(e));
        buf.append(value);
        buf.append(model.getEndTag(e));

        model.setOuterHTML(e, buf.toString());
    }
}
